package com.ruoyi.asms.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.ams.controller.AmsOwnAddressController;
import com.ruoyi.asms.domain.Installation;
import com.ruoyi.asms.domain.InstallationTask;
import com.ruoyi.asms.domain.vo.AddressAndDeptInfoVo;
import com.ruoyi.asms.domain.vo.CreateInstallationTaskVo;
import com.ruoyi.asms.domain.vo.InstallAddressModle;
import com.ruoyi.asms.domain.vo.InstallationWorkOrderVo;
import com.ruoyi.asms.service.AsmsReusingService;
import com.ruoyi.asms.service.impl.InstallationServiceImpl;
import com.ruoyi.asms.service.impl.InstallationTaskServiceImpl;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.AmsOwnAddress;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.security.annotation.PreAuthorize;
import com.ruoyi.security.service.TokensService;
import com.ruoyi.system.controller.SysDeptController;
import com.ruoyi.system.controller.SysUserController;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/asms/installationTask")
public class InstallationTaskController extends BaseController {


    @Autowired
    private InstallationTaskServiceImpl installationTaskService;

    @Autowired
    private InstallationServiceImpl installationService;

    @Autowired
    private AsmsReusingService asmsReusingService;

    @Autowired
    TokensService tokenService;

//    @Autowired
//    RemoteUserService remoteUserService;
//
//    @Autowired
//    private RemoteAssetAddressService remoteAssetAddressService;
//
//    @Autowired
//    private RemoteDeptService remoteDeptService;
    @Autowired
    private SysUserController userController;

    @Autowired
    private AmsOwnAddressController ownAddressController;

    @Autowired
    private SysDeptController deptController;


    @ApiOperation("导入，根据模板文件导入")
    @PostMapping("/importR")
    @ResponseBody
    @PreAuthorize
    public AjaxResult importDataR(@ApiParam(name = "file", value = "excel文件", required = false)MultipartFile file) {

        ExcelUtil<AddressAndDeptInfoVo> util = new ExcelUtil<>(AddressAndDeptInfoVo.class);
        List<AddressAndDeptInfoVo> list = null;

        try {
            list = util.importExcel(file.getInputStream());
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return AjaxResult.error("解析Excel出现错误，请确定数据是否为空并是否按照要求填写！");
        }
        return asmsReusingService.importAddressAndDeptInfo(list);
    }

    @ApiOperation("模板下载")
    @GetMapping("/exportInstallModle")
    public void exportR(HttpServletResponse response) throws IOException {
        ExcelUtil<InstallAddressModle> util = new ExcelUtil<InstallAddressModle>(InstallAddressModle.class);
        List<InstallAddressModle> list = new LinkedList<>();

        InstallAddressModle installAddressModle = new InstallAddressModle();
        list.add(installAddressModle);

        util.exportExcel(response, list, "任务完成情况");
    }

    @ApiOperation("生成任务")
    @PostMapping("/createInstallationTask")
    @Transactional
    public AjaxResult createInstallationTask(@RequestBody CreateInstallationTaskVo vo){
        //检查数据
        List<Long> addressIds = vo.getAddressIds();
        if(addressIds == null || addressIds.size() == 0){
            return AjaxResult.error("请选择好地址");
        }

        //生成任务
        InstallationTask installationTask = new InstallationTask();
        installationTask.setAssetTypeId(vo.getAssetTypeId());
        installationTask.setAssetTypeName(vo.getAssetTypeName());
        installationTask.setContent(vo.getContent());
        installationTask.setStartTime(vo.getStartTime());
        installationTask.setTaskTheme(vo.getTaskTheme());
        installationTask.setCreateBy(SecurityUtils.getUsername());
        installationTask.setCreateTime(System.currentTimeMillis());
        installationTask.setCreateDeptId(SecurityUtils.getDeptId());
        installationTaskService.save(installationTask);

        //生成工单
        Map<Long, AmsOwnAddress> amsOwnAddressMap = ownAddressController.
                getAddressByIds(addressIds.toArray(new Long[addressIds.size()])).getData();
        if(amsOwnAddressMap == null){
            return AjaxResult.error("remoteAssetAddressService 调用失败");
        }

        Set<Long> deptIds = new HashSet<>();

        for(Long aId : amsOwnAddressMap.keySet()){
            AmsOwnAddress amsOwnAddress = amsOwnAddressMap.get(aId);
            deptIds.add(amsOwnAddress.getDeptId());
        }

        Map<Long, SysDept> deptMap = deptController.getDeptMapByIds(deptIds).getData();
        if(deptMap == null){
            return AjaxResult.error("remoteDeptService 调用失败");
        }

        List<Installation> installations = new LinkedList<>();

        for(Long addressId : addressIds){
            Installation installation = new Installation();
            AmsOwnAddress amsOwnAddress = amsOwnAddressMap.get(addressId);

            installation.setAddressId(amsOwnAddress.getAddressId());
            installation.setAddressName(amsOwnAddress.getFullName());

            SysDept sysDept = deptMap.get(amsOwnAddress.getDeptId());

            installation.setDeptId(sysDept.getDeptId());
            installation.setDeptName(sysDept.getDeptFullName());

            installation.setStartTime(vo.getStartTime());
            installation.setInstallationTaskId(installationTask.getInstallationTaskId());
            installation.setInstallationContent(vo.getContent());


            installations.add(installation);
        }

        installationService.saveBatch(installations);

        return AjaxResult.success("任务生成成功。");
    }

    @ApiOperation("获取任务列表")
    @GetMapping("/getInstallationTaskList")
    public TableDataInfo getInstallationTaskList(@ApiParam(name = "deptId", value = "部门id", required = false)Long deptId){

        if(deptId == null){
            deptId = tokenService.getLoginUser().getSysDept().getDeptId();
        }

        startPage();
        List<InstallationTask> installationTaskList = installationTaskService.
                list(new QueryWrapper<InstallationTask>().eq(InstallationTask.CREATE_DEPT_ID, deptId));


        return getDataTable(installationTaskList);
    }

    @ApiOperation("导出任务报表")
    @GetMapping("/installationTaskExport")
    public void installationTaskExport(HttpServletResponse response,@ApiParam(value = "installationTaskId",required = false) Long installationTaskId) throws IOException {

        List<Installation> installationList = installationService.list(new QueryWrapper<Installation>().
                eq(Installation.INSTALLATION_TASK_ID, installationTaskId));

        List<InstallationWorkOrderVo>  orderList = new LinkedList<>();

        Set<Long> userIdSet = new HashSet<>();

        for(Installation installation : installationList){
            InstallationWorkOrderVo installationWorkOrderVo = new InstallationWorkOrderVo();

            BeanUtils.copyProperties(installation,installationWorkOrderVo);
            orderList.add(installationWorkOrderVo);

            if(installation.getUserId() != null && !installation.getUserId().equals(0l)){
                userIdSet.add(installation.getUserId());
            }

        }

        if(userIdSet.size() > 0){
            Map<Long, SysUser> sysUserMap = userController.getUserListByIds(userIdSet.toArray(new Long[userIdSet.size()])).getData();
            if(sysUserMap == null){
               throw new ServiceException("remoteUserService 调用失败");
            }
            if(sysUserMap.size() > 0){
                for(InstallationWorkOrderVo vo : orderList){
                    if(sysUserMap.get(vo.getUserId()) != null){
                        vo.setUserName(sysUserMap.get(vo.getUserId()).getNickName());
                        vo.setUserPhone(sysUserMap.get(vo.getUserId()).getPhonenumber());
                    }

                }
            }

        }


        ExcelUtil<InstallationWorkOrderVo> util = new ExcelUtil<InstallationWorkOrderVo>(InstallationWorkOrderVo.class);

        util.exportExcel(response, orderList, "任务完成情况");

    }
}
